using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using System.Serialization;
using Awaiter;
using Nsb.Classes;
using jQueryApi;

namespace WhirliGig.Classes
{
    [IgnoreNamespace]
    public class EditCss : Ask
    {
        private bool _full;
        private object _src;

        public void EditDAw(Await awp, object cssD)
        {
            _src = cssD;

            cssD = Type.GetField(cssD, "css") ?? cssD;

            Dictionary css =
                new Dictionary(
                    "width", "340px",
                    "height", "380px"
                    );

            string cssTxt = Rx.PrettyJson(cssD ?? new Dictionary(), "\t").ReplaceRegex((RegularExpression)Script.Literal(@"/^{[\r\n]*|[\r\n]*}$|\t/g"), "");

            TextAreaAw(
                awp,
                new Dictionary(
                    "Msg", "Edit raw css",
                    "Value", cssTxt,
                    "Css", css,
                    "Attr", new Dictionary("wrap", "off"),
                    "Customize", (Action)CustomStuff,
                    "Verify",
                    (ActionB)delegate(object result)
                              {
                                  try
                                  {
                                      RePkg((string)result);
                                      Destroy();
                                      return true;
                                  }
                                  catch (Exception ex)
                                  {
                                      Script.Alert(String.Format("Invalid css : {0}", ex));
                                      return false;
                                  }
                              },
                    "Complete",
                    (ActionO)delegate(object result)
                              {
                                  return RePkg((string)result);
                              },
                    "Finally", (Action)Destroy
                    ));
            FullEv(null);
        }

        private object RePkg(string txt)
        {
            if (!_full)
                txt = txt.ReplaceRegex((RegularExpression)Script.Literal(@"/([^,])\s*?\n/g"), "$1,\n"); // Add missing line end commas
            txt = txt.ReplaceRegex((RegularExpression)Script.Literal(@"/[,\s]+?\n/g"), ",\n"); // Remove extra line end commas and spaces
            txt = txt.ReplaceRegex((RegularExpression)Script.Literal(@"/[,\s]+$/g"), ""); // Remove trailing commas and spaces
            if (_full)
                return Json.Parse(txt);
            return Json.Parse("{" + txt + "}");
        }

        private void CustomStuff()
        {
            HiderElement
                .Unbind("mousedown.swallowed")
                .Bind("mousedown.swallowed", delegate { CancelBtn.Click(); })
                ;

            jQuery.FromObject(Document.Body).Bind("keydown.EditCssExamples", delegate(jQueryEvent e) { if (e.Which == 112 /*F1*/) ExamplesEv(e); });

            jQuery.FromHtml("<span/>")
                .AppendTo(Element)
                .CSS(new Dictionary("position", "absolute", "top", 15, "right", 15, "cursor", "pointer", "color", "blue"))
                .Html("[help]")
                .Click(ExamplesEv)
                ;

            //jQuery.FromHtml("<span/>")
            //    .AppendTo(Element)
            //    .CSS(new Dictionary("position", "absolute", "top", 15, "right", 75, "cursor", "pointer", "color", "blue"))
            //    .Html("[advanced]")
            //    .Click(FullEv)
            //    ;
        }

        private void FullEv(jQueryEvent e)
        {
            _full = true;
            jQuery.Select(".Content", Element).Value(Rx.PrettyJson(_src ?? new Dictionary()));
        }

        private void ExamplesEv(jQueryEvent e)
        {
            CancelEvent(e);
            jQueryObject box = jQuery.FromHtml("<div id='EditCssExamples' class='AboveHider Corners20'/>")
                .InsertAfter(Element)
                .CSS(
                    new Dictionary(
                        "position", "absolute",
                        "width", 500,
                        "height", 600,
                        "border", "5px solid green",
                        "background", "#FFC"
                        )
                )
                .Bind("keydown", delegate(jQueryEvent e3) { if (e3.Which == 27 /*esc*/) CloseHelpEv(e3); })
                ;
            box.Plugin<Jewl>().Position(new Dictionary("my", "top center", "at", "top center", "of", Element));

            jQuery.FromHtml("<span/>")
                .AppendTo(box)
                .CSS(new Dictionary("position", "absolute", "top", 12, "right", 10, "cursor", "pointer", "color", "blue"))
                .Html("close")
                .Click(CloseHelpEv)
                ;

            jQuery.FromHtml("<textarea id='EditCssHelpTxt'/>")
                .AppendTo(box)
                .CSS(new Dictionary(
                         "position", "absolute",
                         "top", 34,
                         "right", 8,
                         "bottom", 10,
                         "left", 8,
                         "color", "black",
                         "border", "none",
                         "padding", "3px 5px"
                         ))
            ;

            Keys.FilterAll(box);

            new Await()
                .LoadText("EditCssHelp", Uri.Scripts("Data/EditCssHelp.txt"))
                .HandleDl(Exceptions.BlobLoadError, Await.AbortAw)
                .AddDx(delegate { jQuery.Select("#EditCssHelpTxt").Value((string)Await.Files["EditCssHelp"]).Focus(); })
                .Commit();
        }

        private void CloseHelpEv(jQueryEvent e)
        {
            if (e != null)
                CancelEvent(e);
            jQuery.Select("#EditCssExamples").Remove();
            jQuery.Select(".Content", Element).Focus();
        }

        private void Destroy()
        {
            CloseHelpEv(null);
            jQuery.FromObject(Document.Body).Unbind("keydown.EditCssExamples");
        }
    }
}